package com.quydat.forum.beans;


import com.quydat.forum.entites.UserEntity;
import com.quydat.forum.interfaces.UserEntityManageLocal;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * @author Dat
 * Session Bean implementation class UserEntityManage
 */
@Stateless
public class UserEntityManage implements UserEntityManageLocal {
	/**
	 * Injecting the persistence context.
	 */
	@PersistenceContext(unitName = "forum")
	private EntityManager em;

    /**
     * Default constructor. 
     */
    public UserEntityManage() {
        // TODO Auto-generated constructor stub
    }

	@Override
	public void addUserEntity(UserEntity user) {
		// TODO Auto-generated method stub
		em.persist(user);
		
	}

	@Override
	public void deleteUserEntity(long id) {
		// TODO Auto-generated method stub
	UserEntity user =em.find(UserEntity.class, id);
	em.remove(user);
		
	}

	@Override
	public UserEntity updateUserEntity(long id, UserEntity update) {
		// TODO Auto-generated method stub
		UserEntity alte = em.find(UserEntity.class, id);
		if(alte==null)
		{
			
			return null;
			
		}
		else
		{
			alte.setLoginName(update.getLoginName());
			alte.setPassword(update.getPassword());
			alte.setPosts(update.getPosts());
			alte.setUserGroup(update.getUserGroup());
			em.merge(alte);
			return alte;
		}
		
	}

	@Override
	public UserEntity findUserbyId(long id) {
		return em.find(UserEntity.class, (int)id);
	}

	@Override
	public UserEntity getUserWithLoginNamePasword(String loginName,
			String password) {
		Query query = em.createNamedQuery(UserEntity.GET_USER_WITH_NAME_PASSWORD);
		query.setParameter("loginName", loginName);
		query.setParameter("password", password);
	return (UserEntity)query.getSingleResult();
	}
	

}
